import { writeFileSync, existsSync, mkdirSync } from "fs";
import { defineEventHandler, readBody } from "h3";

export default defineEventHandler(async (event) => {
  const body = await readBody(event);
  const code = body.code;
  const lan = body.lan;

  if (!code) {
    throw createError({
      statusCode: 400,
      statusMessage: "Code is required",
    });
  }

  // Ensure shared-codes directory exists
  const dir = "shared-codes";
  if (!existsSync(dir)) {
    mkdirSync(dir);
  }

  // Generate unique ID
  const id = Date.now().toString(36) + Math.random().toString(36).substring(2);
  const filePath = `${dir}/${id}.json`;

  // Save code to file
  writeFileSync(filePath, JSON.stringify({ code, lan }), "utf-8");

  return { id };
});
